package top.ffhome.security.securityspringboot.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import top.ffhome.security.securityspringboot.model.PermissionDto;
import top.ffhome.security.securityspringboot.model.UserDto;

import java.util.List;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public UserDto getUserByUsername(String username) {
        String sql = "select id,username,password,full_name,mobile from t_user where username=?";
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        if (list != null && list.size() == 1) {
            return list.get(0);
        }
        return null;
    }

    public String[] findPermissionsByUserId(Long userId) {
        String sql = "select distinct p.code from t_permission p, t_role_permission rp, t_user_role ur where p.id=rp.permission_id and rp.role_id=ur.role_id and ur.user_id=?";
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionDto.class));
        return list.parallelStream().map(c -> c.getCode()).toArray(String[]::new);
    }
}
